<?php
require_once 'setup.inc.php';

echo <<<EOL
<!DOCTYPE HTML>
<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>EVE API Registration</title>
    <style type="text/css">
html {
  background-color: #333;
  color: #fff;
  font-family: Arial, Helvetica, sans-serif;
}
a {
  color: #fff;
}
h1 {
  font-size: 1.3em;
  text-align: center;
}
p {
  text-align: center;
}
table {
  width: 600px;
  margin: 1em auto;
  border-collapse: collapse;
}
td {
  font-weight: bold;
  border: 1px solid #000;
  padding: 5px;
}
td[colspan="2"] {
  text-align: center;
  border-style: none;
}
td span {
  font-weight: normal;
  display: block;
  font-size: .85em;
  margin: 5px 0px;
}
select[disabled="disabled"] {
  cursor: pointer;
}
input[name="Key ID"] {
  width: 6em;
}
input[name="Key Ver Code"] {
  width: 20em;
}
input[name="TS UID"] {
  width: 17.5em;
  font-family: monospace;
}
    </style>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
  </head>
  <body>
EOL;

connect_forums_db();

$forums_user_id = get_forums_user_id();

if (empty($_POST)) {
  echo "\n" . <<<EOL
    <h1>
      EVE API Registration
    </h1>
    <form method="post" action=".">
      <table>
        <tr>
          <td>
            EVE API Key ID:
EOL;
  if ($config['Account Key Required']) {
  echo "\n" . <<<EOL
            <span>Choose <strong>"All" in the "Character" dropdown</strong> when you create your key.</span>
EOL;
  }
  echo "\n" . <<<EOL
            <span>Checking the <strong>No Expiry</strong> box is highly recommended.</span>
            <span><a href="https://support.eveonline.com/api/Key/CreatePredefined/{$config['Minimum Access Mask']}" target="_blank">Create an API key</a> (with required access options already chosen for you)</span>
            <span><a href="https://support.eveonline.com/api" target="_blank">View/edit existing keys.</a></span>
          </td>
          <td>
            <input type="text" name="Key ID" autocomplete="off" />
          </td>
        </tr>
        <tr>
          <td>
            EVE API Key Verification Code:
          </td>
          <td>
            <input type="text" name="Key Ver Code" autocomplete="off" maxlength="64" />
          </td>
        </tr>
        <tr>
          <td>
            EVE Character Name:
            <span>Your forums username will be updated to match this exactly upon successful API registration.</span>
          </td>
          <td>
            <select name="Character Name" disabled="disabled">
              <option value="">Click here after entering API info.</option>
            </select>
            <span>This may take a few seconds to update after entering API info.</span>
          </td>
        </tr>
EOL;
  if ($config['Use Teamspeak']) {
    echo "\n" . <<<EOL
        <tr>
          <td>
            Teamspeak Unique ID:
            <span>To find this, open Teamspeak and go to Settings, then Identities, then Unique ID.</span>
            <span>It's also visible in the right panel in Teamspeak when you click on your name while connected to any server.</span>
            <span>If you have multiple identities, choose the one you want to register.</span>
          </td>
          <td>
            <input type="text" name="TS UID" />
          </td>
        </tr>
EOL;
  }
  echo "\n" . <<<EOL
        <tr>
          <td colspan="2">
            <input type="submit" value="Register" />
          </td>
        </tr>
      </table>
    </form>
    <script type="text/javascript">
$(function(){
  $('input:text[name="Key ID"], input:text[name="Key Ver Code"]').change(function () {
    keyID = $('input:text[name="Key ID"]');
    keyVerCode = $('input:text[name="Key Ver Code"]');
    if (keyID.val() !== '' && keyVerCode.val() !== '') {
      $.post('eve-api-get-names.json.php', {'Key ID' : keyID.val(), 'Key Ver Code' : keyVerCode.val()}, function(data, status) {
        if (status != 'success') {
          alert('Error trying to get name list.  Contact an admin.');
        }
        else if (data.error) {
          alert(data.error);
          keyID.val('');
          keyVerCode.val('');
        }
        else {
          if (data.warnings) {
            for (key in data.warnings) {
              alert(data.warnings[key]);
            }
          }
          if (data.names) {
            $('select[name="Character Name"]').empty();
            for (key in data.names) {
              $('select[name="Character Name"]').append('<option value="' + data.names[key] + '">' + data.names[key] + '</option>');
            }
            $('select[name="Character Name"]').removeAttr('disabled');
          }
        }
      }, 'json');
    }
  });
});
    </script>
EOL;
}
else {
  if (empty($_POST['Key_ID']) or empty($_POST['Key_Ver_Code']) or empty($_POST['Character_Name']) or ($config['Use Teamspeak'] and empty($_POST['TS_UID']))) {
    die(<<<EOL
Error: Everything on the registration form was required, but it wasn't all entered.  Use your browser's back button to fix the problem and submit your registration again.
EOL
    );
  }
  $post_db = array_map('mysql_real_escape_string', $_POST);

  if ($config['Use Teamspeak']) {
    //Verify that the TS Unique ID isn't in use by another forums user
    $query = <<<EOL
SELECT User
FROM `EVE Registration`
JOIN {$config['Forums DB']['Table Prefix']}users ON {$config['Forums DB']['Table Prefix']}users.user_id = `EVE Registration`.User
WHERE `TS UID` = "{$post_db['TS_UID']}"
AND User != {$forums_user_id}
EOL;
    $result = mysql_query($query) or die('Error checking for duplicate TS UID.');
    if (mysql_num_rows($result) != 0) {
      die('Error: This Teamspeak Unique ID is already in use by another user.');
    };

    //Verify that the TS Unique ID has been used before on the server (is in the database)
    $ts_server = connect_ts(' - Web') or die('Error connecting to TS server to check whether or not the Teamspeak Unique ID you entered is recognized by the Teamspeak server.');
    $ts_client_db_id = get_ts_user_db_id($ts_server, $_POST['TS_UID']) or die('Error: The Teamspeak Unique ID you entered isn\'t recognized by the Teamspeak server.  It was either entered incorrectly or you\'ve never connected to the server.  Use your browser\'s back button to fix the problem and submit your registration again.');
    if ($ts_client_db_id == -1) {
      die('There was an error verifying whether or not the Teamspeak Unique ID you entered is recognized by the Teamspeak server. Please contact an admin.'); //exception happened and was logged
    }
  }

  //Check API again to verify that the character is in a registered corp
  //  If this isn't done, then any forums user could arbitrarily change their own username
  //  because nothing forces a user to only submit a character name from the prepopulated dropdown.
  $corp = get_eve_corp ($_POST['Key_ID'], $_POST['Key_Ver_Code'], $_POST['Character_Name']) or die('Error getting corporation information with submitted API information.');
  if ($corp == -1) { //connection error
    die('Error connecting to EVE API server to verify corporation membership.  Please try again later.');
  }
  if (!array_key_exists($corp[0], $config['Corps'])) {
    die('Error: The submitted character is not in any of the configured corps.');
  }

  //Update forums username to match character name
  $username_clean = strtolower($post_db['Character_Name']);
  $query = <<<EOL
UPDATE {$config['Forums DB']['Table Prefix']}users
SET
  username = "{$post_db['Character_Name']}",
  username_clean = "{$username_clean}"
WHERE user_id = {$forums_user_id}
EOL;
  mysql_query($query) or die('Error updating your forums username. Please contact an admin.');
  if (mysql_affected_rows()) {
    $query = <<<EOL
UPDATE {$config['Forums DB']['Table Prefix']}topics
SET topic_first_poster_name = "{$post_db['Character_Name']}"
WHERE topic_poster = {$forums_user_id}
EOL;
    mysql_query($query) or log_message('Error updating topic_first_poster_name entries after username change.', FALSE);
    $query = <<<EOL
UPDATE {$config['Forums DB']['Table Prefix']}topics
SET topic_last_poster_name = "{$post_db['Character_Name']}"
WHERE topic_last_poster_id = {$forums_user_id}
EOL;
    mysql_query($query) or log_message('Error updating topic_last_poster_name entries after username change.', FALSE);
  }


  //Add user to registration table, replacing any existing entry (and therefore setting their Cached Until timestamp to NULL)
  if (!$config['Use Teamspeak']) {
    $post_db['TS_UID'] = '';
  }
  $query = <<<EOL
REPLACE INTO `EVE Registration`
(User, `Key ID`, `Key Ver Code`, `TS UID`)
VALUES ("{$forums_user_id}", "{$post_db['Key_ID']}", "{$post_db['Key_Ver_Code']}", "{$post_db['TS_UID']}")
EOL;
  mysql_query($query) or die('Error: Although your forums username did get updated to match your character ID, there was an error finishing the registration process.  Please contact an admin.');
  if ($config['Use Teamspeak']) {
    $teamspeak_text = ' Teamspeak and';
  }
  else {
    $teamspeak_text = '';
  }
  echo <<<EOL
<p>
  Your registration was submitted successfully.  You've been added to the top of the registration bot's queue and will have{$teamspeak_text} forums rights shortly (if not immediately).
</p>
EOL;
  exec('php check-users.php');
}

echo "\n" . <<<EOL
  </body>
</html>
EOL;
?>